<template>
  <div>
    <a-modal :open='props.open' :width="props.modelInfo && props.modelInfo.width ? props.modelInfo.width : '900px'"
      :title="props.modelInfo && props.modelInfo.title ? props.modelInfo.title : 'Basic Modal'" @ok='handleOk'
      okText='保存' :confirmLoading='modelConfig.confirmLoading' :destroyOnClose='modelConfig.destroyOnClose'
      @cancel='handleCancel'>
      <template #footer>
        <a-button key='back' @click='handleCancel'>取消</a-button>
        <a-button key='submit' type='primary' :loading='loading' @click='handleOk'>保存</a-button>
      </template>
      <a-form ref='formRef' name='DictInfoForm' class='ant-advanced-search-form' :model='formState' @finish='onFinish'
        @finishFailed='onFinishFailed' :rules='rulesRef' :label-col='labelCol' :wrapper-col='wrapperCol'>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['typeCode'].name" :label="labelMap['typeCode'].label">
              <a-input v-model:value='formState.typeCode' :placeholder="'请填写' + labelMap['typeCode'].label"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item :name="labelMap['typeName'].name" :label="labelMap['typeName'].label">
              <a-input v-model:value='formState.typeName' :placeholder="'请填写' + labelMap['typeName'].label"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['belongTo'].name" :label="labelMap['belongTo'].label">
              <a-input v-model:value='formState.belongTo' :placeholder="'请填写' + labelMap['belongTo'].label"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item :name="labelMap['belongToName'].name" :label="labelMap['belongToName'].label">
              <a-input v-model:value='formState.belongToName'
                :placeholder="'请填写' + labelMap['belongToName'].label"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['orderBy'].name" :label="labelMap['orderBy'].label">
              <a-input-number style="width: 100%" v-model:value='formState.orderBy'
                :placeholder="'请填写' + labelMap['orderBy'].label"></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item :name="labelMap['isValid'].name" :label="labelMap['isValid'].label">
              <a-input v-model:value='formState.isValid' :placeholder="'请填写' + labelMap['isValid'].label"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang='ts' setup>
import { DictInfoDetail } from './dictInfoDetailTs';
import {
  getDictInfoDetail,
  addOrEditDictInfo,
} from '@/api/commonInfo/dictInfo/dictInfoTs';
import { message, FormInstance } from 'ant-design-vue';
import { ModelInfo } from '../dictInfoListTs';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let loading = ref<boolean>(false);

const formRef = ref<FormInstance>();

const labelMap = ref<any>(
  {
    typeCode: { name: 'typeCode', label: '类别编码' },
    typeName: { name: 'typeName', label: '类别' },
    belongTo: { name: 'belongTo', label: '分类编码' },
    belongToName: { name: 'belongToName', label: '分类' },
    orderBy: { name: 'orderBy', label: '排序' },
    isValid: { name: 'isValid', label: '是否有效' },
  });

const rulesRef = reactive({
  typeCode: [
    {
      required: true,
      message: '类别编码不能为空！',
    },
  ],
  typeName: [
    {
      required: true,
      message: '类别不能为空！',
    },
  ],
  belongTo: [
    {
      required: true,
      message: '分类编码不能为空！',
    },
  ],
  belongToName: [
    {
      required: true,
      message: '分类不能为空！',
    },
  ],
  orderBy: [
    {
      required: true,
      message: '排序不能为空！',
    },
  ],
  isValid: [
    {
      required: true,
      message: '是否有效不能为空！',
    },
  ],
});

const modelConfig = {
  confirmLoading: true,
  destroyOnClose: true,
};

interface Props {
  open?: boolean;
  modelInfo?: ModelInfo;
}
const props = defineProps<Props>();

let formState = ref<DictInfoDetail>({});


const emit = defineEmits(['handleOk', 'handleCancel']);

const handleOk = (): void => {
  loading.value = true;
  if (formRef.value) {
    formRef.value.validateFields().then(
      () => saveDictInfoManager()).catch(() => {
        loading.value = false;
      });
  }
};

const handleCancel = (): void => {
  emit('handleCancel', false);
};

//保存字典信息表信息
const saveDictInfoManager = (): void => {
  let method = '';
  if (formState.value.id) {
    method = 'put';
  } else {
    method = 'post';
  }
  addOrEditDictInfo(method, formState.value)
    .then((res) => {
      if (res.code == '200') {
        message.success((res && res.message) || '保存成功！');
        emit('handleOk', false);
      } else {
        message.error((res && res.message) || '保存失败！');
      }
      formState.value = {};
    })
    .catch((error: any) => {
      message.error((error?.message) || '保存失败！');
    }).finally(() => {
      loading.value = false;
    });
}

const onFinish = (values: any): void => {
  console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any): void => {
  console.log('Failed:', errorInfo);
};

const init = (): void => {
  if (props.modelInfo) {
    if (props.modelInfo.id) {
      getDictInfoDetail(props.modelInfo.id)
        .then((res) => {
          if (res.code == '200') {
            formState.value = res.data;
            modelConfig.confirmLoading = false;
          } else {
            message.error((res && res.message) || '查询失败！');
          }
        })
        .catch((error: any) => {
          message.error((error?.message) || '查询失败！');
        });
    } else {
      modelConfig.confirmLoading = false;
      formState.value = {
      };
    }
  }
}

watch(
  () => props.open,
  (newVal) => {
    if (newVal) {
      init();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

defineExpose({ handleOk, handleCancel });
</script>
<style lang='scss' scoped>
@import '@/style/index.scss';
</style>